package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
)

// build under some dir

// Compile todo
func (be *BaliExecutor) Compile(workdir string) error {
	balisrc := filepath.Join(workdir, "balisrc.json")
	if !PathExists(balisrc) {
		fmt.Fprintf(os.Stderr, "%s not exists\n", balisrc)
		return os.ErrNotExist
	}
	var bsm BaliSrcMetadata
	if err := LoadMetadata(balisrc, &bsm); err != nil {
		fmt.Fprintf(os.Stderr, "load %s error %s\n", balisrc, err)
		return err
	}
	if len(bsm.Name) == 0 {
		bsm.Name = filepath.Base(workdir)
	} else {
		bsm.Name = filepath.Base(bsm.Name)
	}
	if bsm.Name == "." {
		return ErrorCat("bad name: ", bsm.Name)
	}
	// Update version
	be.UpdateNow(bsm.Version)
	binaryName := be.BinaryName(workdir, bsm.Name)
	cmd := exec.Command("go", "build", "-o", binaryName)
	for _, s := range bsm.GoFlags {
		// Append other args
		cmd.Args = append(cmd.Args, be.ExpandEnv(s))
	}
	cmd.Env = be.Environ
	cmd.Dir = workdir
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	fmt.Fprintf(os.Stderr, "go compile \x1b[32m%s\x1b[0m version: \x1b[32m%s\x1b[0m\n", bsm.Name, bsm.Version)
	fmt.Fprintf(os.Stderr, "\x1b[34m%s\x1b[0m\n", cmd.String())
	if err := cmd.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "compile %s error \x1b[31m%s\x1b[0m\n", bsm.Name, err)
		return err
	}
	bindir := filepath.Join(be.Out, bsm.Destination)
	_ = os.MkdirAll(bindir, 0775)
	binfile := filepath.Join(workdir, binaryName)
	destfile := filepath.Join(be.Out, bsm.Destination, binaryName)
	if err := os.Rename(binfile, destfile); err != nil {
		return err
	}
	be.Binaries = append(be.Binaries, destfile)
	return nil
}
